//
//  NSTextView+WCExtensions.m
//  WabbitCode
//
//  Created by William Towe on 12/2/08.
//  Copyright 2008 Revolution Software. All rights reserved.
//

#import "NSTextView+WCExtensions.h"
#import "WCTextView.h"


@implementation NSTextView (WCExtensions)
- (NSRange)completeRange; {
	return NSMakeRange(0, [[self string] length]);
}
- (NSRange)visibleRange; {
	NSString *string = [self string];
	
	if (![string length])
		return NSMakeRange(0, 0);
	
	NSRect visibleRect = [[[self enclosingScrollView] contentView] documentVisibleRect];
	NSRange visibleRange = [[self layoutManager] glyphRangeForBoundingRect:visibleRect inTextContainer:[self textContainer]];
	NSUInteger firstChar = [string lineRangeForRange:NSMakeRange(visibleRange.location, 0)].location;
	NSUInteger lastChar = NSMaxRange([string lineRangeForRange:NSMakeRange(NSMaxRange(visibleRange), 0)]);
	
	return NSMakeRange(firstChar, lastChar-firstChar);
}

- (NSRange)selectedLineRange; {
	NSString *string = [self string];
	
	if (![string length])
		return NSMakeRange(0, 0);
	
	return [string lineRangeForRange:[self selectedRange]];
}

- (NSString *)selectedString; {
	NSRange range = [self selectedRange];
	
	if (!range.length)
		return nil;
	
	return [[self string] substringWithRange:range];
}

- (void)setSelectedRangeSafely:(NSRange)range; {
	if (NSMaxRange(range) > [[self string] length]) {
		[self setSelectedRange:NSMakeRange(0, 0)];
#ifdef WCDEBUG
		NSLog(@"Range out of bounds: %@", NSStringFromRange(range));
#endif
		return;
	}
	[self setSelectedRange:range];
}
@end
